# python detect_drowsiness.py --shape-predictor shape_predictor_68_face_landmarks.dat
# python detect_drowsiness.py --shape-predictor shape_predictor_68_face_landmarks.dat --alarm alarm.wav
from scipy.spatial import distance as dist
from imutils.video import VideoStream   #视频流
from imutils import face_utils          #人脸检测    图像处理包
from threading import Thread
import numpy as np
import playsound  #声音播报
import argparse
import imutils
import time
import dlib   #比OpenCV更加精准的图片人脸检测Dlib库
import cv2

def sound_alarm(path):   #声音播报
	# play an alarm sound
	playsound.playsound(path)

def eye_aspect_ratio(eye):  #返回人眼纵横比

	A = dist.euclidean(eye[1], eye[5])     # P2-P6
	B = dist.euclidean(eye[2], eye[4])      #P3-P5
	C = dist.euclidean(eye[0], eye[3])     # P1-P4
	ear = (A + B) / (2.0 * C)      #  (P2-P6)*(P3-P5)/(P1-P4)

	return ear
# detect_blinks.py脚本需要一个命令行参数，然后第二个是可选的参数：
# 1.--shape-predictor：这是dlib的预训练面部标志检测器的路径。
# 2.--video：它控制驻留在磁盘上的输入视频文件的路径。如果您想要使用实时视频流，则需在执行脚本时省略此开关。
ap=argparse()
ap.add_argument("-p", "--shape-predictor", required=True, help="path to facial landmark predictor")  #预测器
ap.add_argument("-a", "--alarm", type=str, default="", help="path alarm .WAV file")  #报警声音的地址
ap.add_argument("-w", "--webcam", type=int, default=0, help="index of webcam on system")
args = vars(ap.parse_args())

EYE_AR_THRESH = 0.3   #眼睛的阈值
EYE_AR_CONSEC_FRAMES = 5  #超过指定帧数即为疲劳

COUNTER = 0   #用于计数帧数
ALARM_ON = False  #警报初始化状态为False


print("[INFO] loading facial landmark predictor...")
# 定义人脸检测器
detector = dlib.get_frontal_face_detector()  #构建人脸框位置检测器
predictor = dlib.shape_predictor(args["shape_predictor"])  #绘制人脸关键点检测器

#为下面的左眼和右眼提取（x，y）坐标的起始和结束数组切片索引值
(lStart, lEnd) = face_utils.FACIAL_LANDMARKS_IDXS["left_eye"]   #这个是对68个点的描述，取出左眼
(rStart, rEnd) = face_utils.FACIAL_LANDMARKS_IDXS["right_eye"]   #这个是对68个点的描述，取出右眼

#决定是否使用基于文件的视频流或实时USB/网络摄像头/ Raspberry Pi摄像头视频流：
print("[INFO] starting video stream thread...")
vs = VideoStream(src=args["webcam"]).start()  #开启视频头，开启视频头的源头，一般webcam为自带的摄像头
time.sleep(1.0)

while True:

	frame = vs.read()
	frame = imutils.resize(frame, width=450)
	gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

	rects = detector(gray, 0)  #返回人脸信息
	print('rects:', rects)

	for rect in rects:

		shape = predictor(gray, rect)  #绘制人脸关键点检测器进行预测
		shape = face_utils.shape_to_np(shape)  #转化为np.array类型

		leftEye = shape[lStart:lEnd]    #提取左右眼
		rightEye = shape[rStart:rEnd]
		leftEAR = eye_aspect_ratio(leftEye)  #进行纵横比的运算
		rightEAR = eye_aspect_ratio(rightEye)
		ear = (leftEAR + rightEAR) / 2.0  #得到比率ear

		leftEyeHull = cv2.convexHull(leftEye)  #通过convexHull函数，我们就能得到轮廓的凸包
		rightEyeHull = cv2.convexHull(rightEye)
		cv2.drawContours(frame, [leftEyeHull], -1, (0, 255, 0), 1)    #在图中进行绘画出效果
		cv2.drawContours(frame, [rightEyeHull], -1, (0, 255, 0), 1)

		if ear < EYE_AR_THRESH:
			COUNTER += 1
			if COUNTER >= EYE_AR_CONSEC_FRAMES:
				if not ALARM_ON:
					ALARM_ON = True
					if args["alarm"] != "":
						t = Thread(target=sound_alarm,
							args=(args["alarm"],))
						t.deamon = True  #警报关闭，线程也随之关闭
						t.start()
				cv2.putText(frame, "DROWSINESS ALERT!", (10, 30),
					cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
		else:
			COUNTER = 0
			ALARM_ON = False

		cv2.putText(frame, "EAR: {:.2f}".format(ear), (300, 30),
			cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)

	cv2.imshow("Frame", frame)
	key = cv2.waitKey(1) & 0xFF
	if key == ord("q"):
		break

cv2.destroyAllWindows()
vs.stop()